package mspbots.qbd.data.online.bill;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.qbd.common.ResultMsg;
import mspbots.qbd.data.BaseReceiver;
import mspbots.qbd.data.online.invoice.OnlineInvoice;
import mspbots.qbd.data.online.invoice.OnlineInvoiceRepository;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

@Log4j2
@Component
@RequiredArgsConstructor
public class OnlineBillReceiver extends BaseReceiver {
    private final OnlineBillRepository billRepository;

    @RabbitListener(queues = "quick-books-online.bill.sync")
    public void processUsers(ResultMsg resultMsg) {

        OnlineBill data = OnlineBill.builder().otherId(resultMsg.getId()).build();
        data.setTenantId(resultMsg.getTenantId());
        ZonedDateTime createdDateTime = ZonedDateTime.parse(resultMsg.getEntity().get("MetaData")
                .get("CreateTime").asText(), DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        ZonedDateTime modifiedDateTime = ZonedDateTime.parse(resultMsg.getEntity().get("MetaData")
                .get("LastUpdatedTime").asText(), DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        createdDateTime = createdDateTime.withZoneSameInstant(ZoneOffset.UTC);
        modifiedDateTime = modifiedDateTime.withZoneSameInstant(ZoneOffset.UTC);
        data.setCreatedTime(createdDateTime.toLocalDateTime());
        data.setUpdatedTime(modifiedDateTime.toLocalDateTime());
        data.setExtend(resultMsg.getEntity());
        data.setSyncTime(LocalDateTime.now());

        this.billRepository.findByOtherIdAndTenantId(data.getOtherId(), data.getTenantId())
                .map(account -> {
                    data.setId(account.getId());
                    return data;
                })
                .defaultIfEmpty(data)
                .flatMap(this.billRepository::save).block(Duration.ofSeconds(10));

    }
}
